package com.ysalliance.getFan.organization.ui;

import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ysalliance.getFan.organization.Bean.ClassBean;
import com.ysalliance.getFan.organization.Bean.ClassSituationBean;
import com.ysalliance.getFan.organization.Bean.TaskBean;
import com.ysalliance.getFan.organization.Bean.bus.ChangeClassNameBean;
import com.ysalliance.getFan.organization.Bean.bus.DeleteClassBean;
import com.ysalliance.getFan.organization.Bean.bus.TaskAddIsNeedFresh;
import com.ysalliance.getFan.organization.Bean.bus.TaskDeleteIsNeedFresh;
import com.ysalliance.getFan.organization.Bean.bus.TaskUpdateIsNeedFresh;
import com.ysalliance.getFan.organization.Bean.multilist.FirstTimeBean;
import com.ysalliance.getFan.organization.LucasUtil;
import com.ysalliance.getFan.organization.R;
import com.ysalliance.getFan.organization.adapter.TaskMultiListAdapter;
import com.ysalliance.getFan.organization.myview.FunButton;
import com.ysalliance.getFan.organization.network.Network;
import com.ysalliance.getFan.organization.ui.base.LucasBaseActivity;
import com.ysalliance.getFan.organization.ui.task.AddTaskActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

import static com.ysalliance.getFan.organization.FanerConstant.CHANGE_CLASS_NAME;
import static com.ysalliance.getFan.organization.adapter.TaskMultiListAdapter.ITEM_FIRST_LEVEL;


/**
 * 具体班级
 * @author lucas
 * created at 2020-02-24 14:54
 */
public class ClassroomActivity extends LucasBaseActivity {

    //用户协议
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.img_class_manager)
    ImageView img_class_manager;
    @BindView(R.id.funbt_enter)
    FunButton funbt_enter;    //立即入驻
    @BindView(R.id.tv_tag)
    TextView tv_tag;   //TextView提示
    @BindView(R.id.recycler)
    RecyclerView recycler;


    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private CustomPopWindow mCustomPopWindow;

    private TaskMultiListAdapter taskMultiListAdapter;


    public ClassBean  classBean;

    private List<MultiItemEntity> list_Multi = new ArrayList<>();

    private int page = 1;
    private int count = 1;

    @Override
    public int bindContentView() {
        return R.layout.activity_classroom;
    }

    @Override
    public void beforeView() {
        super.beforeView();
        EventBus.getDefault().register(mContext);
    }

    @Override
    public void afterView() {
        super.afterView();


        classBean = (ClassBean)getIntent().getSerializableExtra("class_info");


        tv_tag.setText("您还未添加任务");
        funbt_enter.setTvTag("添加任务");
        funbt_enter.setFunbt_Img(R.mipmap.funbt_add);
        tv_title.setText(classBean.getName());




        //下拉刷新的响应事件
        MaterialHeader header = new MaterialHeader(mContext);
        header.setColorSchemeColors(Color.parseColor("#2f384a"));
        refreshLayout.setRefreshHeader(header);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getClassTask(classBean.getId(), page);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //加载范儿视频
                page = page +1 ;
                getClassTask(classBean.getId(), page);
            }
        });



        //--------------------------列表适配器--------------------------
        //Adapter适配器初始化
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        //设置列表默认动画效果
        recycler.setItemAnimator(new DefaultItemAnimator());
        //绑定适配器
        taskMultiListAdapter = new TaskMultiListAdapter(list_Multi);
        recycler.setAdapter(taskMultiListAdapter);
//        //列表点击事件
//        taskMultiListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                ToastUtils.showShort("fjdskjf从开发的思路");
//            }
//        });
        //--------------------------适配器--------------------------





        initClick();


        page = 1;
        getClassTask(classBean.getId(), page);


    }





    public void initClick() {

        // 班级管理 or 添加任务
        img_class_manager.setOnClickListener(v->{
            showPopMenu(img_class_manager);
        });
        // 添加任务
        funbt_enter.setOnClickListener(v->{
            Intent intent = new Intent(Utils.getApp(), AddTaskActivity.class);
            intent.putExtra("class_info", classBean);
            ActivityUtils.startActivity(intent);
        });


    }


    /** popupwindow  */
    private void showPopMenu(View view) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_menu_class, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int  mShowMorePopupWindowWidth = -contentView .getMeasuredWidth();
        int  mShowMorePopupWindowHeight = -contentView .getMeasuredHeight();


        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .create()
                .showAsDropDown(view,mShowMorePopupWindowWidth + 100,0);
    }
    private void handleLogic(View contentView){
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mCustomPopWindow!=null){
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()){
                    case R.id.menu1_class_manager:
                        //班级管理
                        Intent intent1 = new Intent(Utils.getApp(), ClassManagerActivity.class);
                        intent1.putExtra("class_info", classBean);
                        intent1.putExtra("class", CHANGE_CLASS_NAME);
                        ActivityUtils.startActivity(intent1);
                        break;
                    case R.id.menu2_add_task:
                        //添加任务
                        Intent intent = new Intent(Utils.getApp(), AddTaskActivity.class);
                        intent.putExtra("class_info", classBean);
                        ActivityUtils.startActivity(intent);
                        break;

                }
            }
        };
        contentView.findViewById(R.id.menu1_class_manager).setOnClickListener(listener);
        contentView.findViewById(R.id.menu2_add_task).setOnClickListener(listener);
    }


    /**  获取某一班级任务   */
    public void getClassTask(String class_id, int page){

        if(list_Multi.size()>=count){
            if(page!=1){
                ToastUtils.showShort("已经到底");
                stopLoadRefresh();
                return;
            }
        }

        disposable = Network.getUtilApi()
                .getClassTask(class_id, page+"")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        String res = responseBody.string();
                        LogUtils.json("获取某一班级任务的返回", res);

                        stopLoadRefresh();

                        JSONObject jsonObject = new JSONObject(  res  );
                        if(LucasUtil.isok(jsonObject.optString("status"))){

                            JSONObject jsonObject_data = new JSONObject(  jsonObject.optString("data")  );

                            count = jsonObject_data.optInt("count");
                            if(count ==0 ){
                                //任务为0显示添加任务
                                recycler.setVisibility(View.GONE);
                                tv_tag.setVisibility(View.VISIBLE);
                                funbt_enter.setVisibility(View.VISIBLE);
                                return;
                            }else {
                                recycler.setVisibility(View.VISIBLE);
                                tv_tag.setVisibility(View.GONE);
                                funbt_enter.setVisibility(View.GONE);
                            }



                            List<ClassSituationBean> list = new Gson().fromJson( jsonObject_data.optString("results"), new TypeToken<List<ClassSituationBean>>(){}.getType());


                            if(page == 1) {
                                list_Multi.clear();
                                for (int i = 0; i < list.size(); i++) {
                                    FirstTimeBean item0 = new FirstTimeBean(list.get(i).getMonth() );
                                    for (int j = 0; j < list.get(i).getTasks().size(); j++) {
                                        TaskBean item1 = list.get(i).getTasks().get(j);
                                        item0.addSubItem(item1);
                                    }
                                    list_Multi.add(item0);
                                }
                            }else {


                                //添加同一个月内的
                                for(int i = 0 ; i < list.size(); i++){
                                    FirstTimeBean firstTimeBean = new FirstTimeBean(list.get(i).getMonth() );
                                    for(int j = 0; j <  list_Multi.size(); j++){
                                        if(list_Multi.get(j).getItemType() == ITEM_FIRST_LEVEL){

                                            if(((FirstTimeBean)list_Multi.get(j)).getCreate_time().equals(firstTimeBean.getCreate_time())){

                                                list_Multi.addAll(list.get(i).getTasks());
                                                //去掉添加的同一个月内的
                                                list.remove(i);
                                            }
                                        }
                                    }
                                }

                                //添加剩下的月的
                                for (int i = 0; i < list.size(); i++) {
                                    FirstTimeBean item0 = new FirstTimeBean(list.get(i).getMonth() );
                                    for (int j = 0; j < list.get(i).getTasks().size(); j++) {
                                        TaskBean item1 = list.get(i).getTasks().get(j);
                                        item0.addSubItem(item1);
                                    }
                                    list_Multi.add(item0);
                                }



                            }



                            taskMultiListAdapter.notifyDataSetChanged();


                        }else {
                            ToastUtils.showShort(jsonObject.optString("message"));
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        Toast.makeText(mContext,"网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });
    }





    public void stopLoadRefresh() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }





    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DeleteClassBean deleteClassBean) {
        /* Do something */
        LogUtils.e("收到了eventbus的删除班级的提示");
        /* Do something */
        if(deleteClassBean.isdelete){
            finish();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ChangeClassNameBean changeClassNameBean) {
        /* Do something */
        LogUtils.e("收到了eventbus的更新班级名称的提示");
        /* Do something */
        classBean.setName(changeClassNameBean.getClass_name());
        tv_title.setText(classBean.getName());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskUpdateIsNeedFresh taskUpdateIsNeedFresh) {
        /* Do something */
        LogUtils.e("收到了是否需要刷新任务详情页与否的提示");
        /* Do something */
        if(taskUpdateIsNeedFresh.isIs_need_fresh()){
            page = 1;
            getClassTask(classBean.getId(), page);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskDeleteIsNeedFresh taskDeleteIsNeedFresh) {
        /* Do something */
        LogUtils.e("收到了是否需要删除任务详情页与否的提示");
        /* Do something */
        if(taskDeleteIsNeedFresh.isIs_need_fresh()){
            page = 1;
            getClassTask(classBean.getId(), page);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskAddIsNeedFresh taskDeleteIsNeedFresh) {
        /* Do something */
        LogUtils.e("收到了是否需要删除任务详情页与否的提示");
        /* Do something */
        if(taskDeleteIsNeedFresh.isIs_need_fresh()){
            page = 1;
            getClassTask(classBean.getId(), page);
        }
    }






    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
